package com.uestc.shop.web;

import com.uestc.shop.base.PhotoUtils;
import com.uestc.shop.domain.Product;
import com.uestc.shop.domain.User;
import com.uestc.shop.domain.dto.ProductAddDto;
import com.uestc.shop.service.IProductService;
import com.uestc.shop.service.IUserService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * @Package: com.uestc.shop.web
 * @author: Jounghu
 * @date: 2018/7/26 1:29
 * @version: V1.0
 */
@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    IProductService productService;

    @Autowired
    IUserService userService;


    @PostMapping("/add")
    public String addProduct(ProductAddDto productAddDto, HttpServletRequest request) {
        String username = (String) request.getSession().getAttribute("user");
        if (StringUtils.isEmpty(username)) {
            // 没有登录
            return "redirect:/login";
        }

        User user = userService.findUserByName(username);
        Product product = modelMapper.map(productAddDto, Product.class);

        // 默认都是手机0
        // 这里随机一下
        product.setMainImage(PhotoUtils.randomPhoto());

        product.setCreator(username);
        product.setCreatorId(user.getId());
        Product entity = productService.save(product);
        if (entity == null) {
            // 插入失败
            request.setAttribute("product", productAddDto);
            request.setAttribute("error", "插入失败!");
        }
        request.setAttribute("product",new ProductAddDto());
        request.setAttribute("success", "插入成功!");
        return "product";
    }

}
